<template>
	<!-- 面包屑导航 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>课程管理</el-breadcrumb-item>
		<el-breadcrumb-item>课程信息管理</el-breadcrumb-item>
	</el-breadcrumb>
	
	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="margin: 10px -10px;">
		<el-form-item label="课程名称">
			<el-input v-model="queryInfo.courseName" placeholder="请输入课程名称" clearable @clear="query" />
		</el-form-item>
		<el-form-item label="课程分类">
			<el-select v-model="queryInfo.sort.sort" placeholder="请选择课程分类" clearable @clear="query">
				<el-option v-for="item in options" :label="item.sort" :value="item.sort" />
			</el-select>
		</el-form-item>
		<el-form-item label="心理师名">
			<el-input v-model="queryInfo.consultant.consultantName" placeholder="请输入心理师名" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="query">搜索</el-button>
			<el-button type="primary" @click="add">新增课程</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>
	
	 
	
	<!-- 数据表格 -->
	<el-table ref="multipleTableRef" :data="dataList" style="width: 100%" @selection-change="handleSelectionChange" border>
		<el-table-column type="selection" width="50" />
		<el-table-column align="center" property="id" label="ID" width="55" >
			<template #default="scope">
			      <!-- scope.$index 是当前行的索引（从 0 开始） -->
			      {{ scope.$index + 1 }}
			</template>
		</el-table-column>
		<el-table-column align="center" property="courseName" label="课程名称" />
		<el-table-column align="center" property="courseTime" label="时长" >
			<template #default="scoped">
						{{ formatTimes(scoped.row.courseTime) }}
				</template>
		</el-table-column>
		<el-table-column align="center" property="courseVideocount"  label="视频数量" />
		<el-table-column align="center" property="courseLearncount" label="学习量" />
		<el-table-column align="center" property="courseDescription" label="简介"/>
		<el-table-column align="center" property="coursePrice" label="价格" />
		<el-table-column align="center" property="sort.sort" label="分类" />
		<el-table-column align="center" property="consultant.consultantName" label="心理导师名" />
		<el-table-column align="center" fixed="right" label="操作" width="220">
			<template #default="scope">
				<el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
				<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	
	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />
	
	
	<!-- 新增和修改对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="addOrUpdate" label-width="100">
			<el-form-item label="课程名称">
				<el-input v-model="addOrUpdate.courseName" autocomplete="off" placeholder="请输入课程名称"></el-input>
			</el-form-item>
			<el-form-item label="课程封面图">
				  <el-upload
					v-model:file-list="fileList" 
					action="http://localhost:8080/upload"
					list-type="picture-card"
					limit="1"
					:on-preview="handlePictureCardPreview"
					:on-success="handleAvatarSuccess"
					:on-remove="handleRemove"
				  >
					<el-icon><Plus /></el-icon>
				</el-upload>
				  <el-dialog v-model="dialogImageVisible">
				    <img w-full :src="dialogImageUrl" alt="Preview Image" />
				  </el-dialog>
				  </el-form-item>
			<el-form-item label="适用人群">
				<el-input  type="textarea" v-model="addOrUpdate.coursePeople"  autocomplete="off" placeholder="请输入适用人群"></el-input>
			</el-form-item>
			<el-form-item label="学习收获">
				<el-input v-model="addOrUpdate.courseLearning" autocomplete="off" placeholder="请输入学习收获"></el-input>
			</el-form-item>
			<el-form-item label="订阅须知">
				<el-input v-model="addOrUpdate.courseSubscribe" type="textarea" autocomplete="off" placeholder="请输入订阅须知"></el-input>
			</el-form-item>
			<el-form-item label="课程原价格">
				<el-input v-model="addOrUpdate.coursePrice" autocomplete="off" placeholder="请输入课程价格"></el-input>
			</el-form-item>
			<el-form-item label="课程折扣价">
				<el-input v-model="addOrUpdate.courseDprice" autocomplete="off" placeholder="请输入课程价格"></el-input>
			</el-form-item>
			<el-form-item label="心理师名">
				<el-input v-model="addOrUpdate.consultant.consultantName" autocomplete="off" placeholder="请输入心理导师名"></el-input>
			</el-form-item>
			
			<el-form-item label="课程分类">
				<el-select v-model="addOrUpdate.sort.id" placeholder="请选择课程分类">
					<el-option v-for="item in options" :label="item.sort" :value="item.id" :key="item.value" /> 
				</el-select>
			</el-form-item>
			
			<el-form-item label="课程简介">
				<el-input v-model="addOrUpdate.courseDescription" type="textarea" placeholder="请输入课程简介"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
	
</template>

<script setup>
	import {getCurrentInstance,reactive} from 'vue';
	import {ref,onMounted} from 'vue';
	import {ElMessage,ElMessageBox} from 'element-plus';
	import { cloneDeep } from 'lodash-es';
	import {Plus} from '@element-plus/icons-vue';
	import qs from 'qs';
import http from '@/util/http';
	
	const total = ref(0);
	
	/* 查询信息对象 */
	const queryInfo = reactive({
		courseName:'',
		sort:{
			sort:undefined
		},
		consultant:{
			consultantName:''
		},
		pageSize:10,
		pageNum:1
	})
	
	const dialogImageVisible=ref(false)
	const dialogImageUrl=ref('')
	const fileList=ref([])

	//分类数组对象
	const options=ref([])

	const imgUrl = ref('')
	//当前页数据
	const dataList = ref([])
	//存储复选数据
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	 
		
	//查询数据的函数
	const query = () => {
		axios.get(`course/page`, {
				params: queryInfo,
				paramsSerializer: (params) => {
     			return qs.stringify(params, {
       				allowDots: true, // 启用点号格式
        			skipNulls: true  // 可选：跳过空值
     		 	});
  		  	}
		})
			
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error('查询数据失败')
				}
	
			})
	};

	//查询分类
	const queryTypeList=()=>{
		axios.get(`courseSort/select`).then((resp)=>{
			if (resp.code === 200) {
				options.value=resp.data;
				console.log(resp.data);
			}
		})
	}
	
	//组件加载完毕，查询数据
	onMounted(() => {
		query();
		queryTypeList();
	});
	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		query();
	};
	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		query();
	};
	
	const title = ref('新增课程')
	const dialogFormVisible = ref(false)
	//新增修改数据集
	const addOrUpdate = ref({
		id:'',
		courseName:'',
		coursePic:'',
		coursePrice:0,
		courseDprice:0,
		courseVideocount:0,
		courseLearncount:0,
		courseTime:'',
		courseDescription:'',
		coursePeople:'',
		courseLearning:'',
		courseSubscribe:'',
		courseTeacher:'',
		courseSort:'',
		sort:{
			id:'',
			sort:''
		},
		consultant:{
			consultantName:''
		}
	
	})
	
	//当点击关闭按钮 或 取消按钮的时候，重置表单
	const cancle = () => {
		console.log('你点击了取消按钮');
		addOrUpdate.value = {
		id:'',
		courseName:'',
		coursePic:'',
		coursePrice:'',
		courseDprice:'',
		courseVideocount:0,
		courseLearncount:0,
		courseTime:'',
		courseDescription:'',
		coursePeople:'',
		courseLearning:'',
		courseSubscribe:'',
		courseTeacher:'',
		sort:{
			sort:''
		},
		consultant:{
			consultantName:''
		}
		}
		dialogFormVisible.value = false
		fileList.value=[]
	}
	
	//确定按钮
	const confirm = () => {
		console.log('你点击了确定按钮');
		if (addOrUpdate.value.id) { //数据存在id，修改
			axios.put('course/update', addOrUpdate.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		} else { //新增
			axios.post('course/add', addOrUpdate.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		}
	}
	
	//点击新增按钮的时候，弹出对话框
	const add = () => {
		//title.value = '新增咨询师'
		dialogFormVisible.value = true
	}
	//编辑
	const edit = (row) => {
		title.value = '编辑课程'
		dialogFormVisible.value = true
		console.log(row);
		fileList.value=[];
		addOrUpdate.value = cloneDeep(row) 
		var listView = addOrUpdate.value.coursePic;
       if (listView) {
           fileList.value.push({
               name: listView.substr(listView.lastIndexOf('/') + 1),
               url: 'http://localhost:8080' + listView
           })
		}
		console.log(addOrUpdate.value.coursePic);
		
		
	}
	//单个删除
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?','Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete(`course/delete/${id}`)
				.then(resp => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	//批量删除
	const batchRemove = () => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?','Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete('course/delete', {
					params: {
						ids: multipleSelection.value.join(',')
					}
				})
				.then(resp => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}

		//图片上传成功的回调函数
	const handleAvatarSuccess=(resp)=>{
		addOrUpdate.value.coursePic=resp.data
	}

		//用来计算毫秒值转换为时分秒
	const formatTimes =(ms)=>{
		console.log(ms);
		
		if (ms === null || ms === undefined) return '00:00:00'

		
      const totalSeconds = Math.floor(ms / 1000)
      const hours = Math.floor(totalSeconds / 3600)
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      const seconds = totalSeconds % 60
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        seconds.toString().padStart(2, '0')
      ].join(':')
	}
</script>

<style scoped>
.el-breadcrumb {
		height: 20px;
		font-size: 15px;
		border-bottom: 1px solid #eee;
		padding-bottom: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-pagination {
		margin-top: 15px;
	}
</style>